<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件同步工具</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">
    <style>
        /* 目录容器样式 */
        .directory-container {
            border: var(--bs-border-width) var(--bs-border-style) var(--bs-border-color);
            border-radius: var(--bs-border-radius);
            padding: var(--bs-card-spacer-y) var(--bs-card-spacer-x);
            background-color: var(--bs-body-bg);
            box-shadow: var(--bs-box-shadow-sm);
        }

        /* 文件列表样式 */
        .file-list {
            height: 80vh;
            overflow-y: auto;
            border: var(--bs-border-width) var(--bs-border-style) var(--bs-border-color);
            padding: var(--bs-card-spacer-y) var(--bs-card-spacer-x);
            border-radius: var(--bs-border-radius);
            background-color: var(--bs-body-bg);
            box-shadow: var(--bs-box-shadow-sm);
        }

        /* 文件项样式 */
        .file-item {
            cursor: pointer;
            padding: 0.5rem 0.75rem;
            margin: 0.25rem 0;
            border-radius: 0.5rem;
            display: flex;
            align-items: center;
            transition: all 0.2s ease-in-out;
            border: 2px solid transparent;
        }
        .file-item:hover {
            background-color: var(--bs-gray-100);
            transform: translateX(2px);
        }
        .file-item.selected {
            background-color: var(--bs-primary-bg-subtle);
            border-color: var(--bs-primary);
            box-shadow: 0 0 0 1px var(--bs-primary);
        }
        .file-item.different {
            background-color: var(--bs-warning-bg-subtle);
            border-color: var(--bs-warning);
        }
        .file-item.missing {
            background-color: var(--bs-danger-bg-subtle);
            border-color: var(--bs-danger);
        }

        /* 图标样式 */
        .file-icon {
            margin-right: 0.625rem;
            width: 1.25rem;
            text-align: center;
            color: var(--bs-gray-600);
        }
        .folder-icon {
            color: var(--bs-warning);
        }
        .image-icon {
            color: var(--bs-purple);
        }
        .document-icon {
            color: var(--bs-primary);
        }
        .code-icon {
            color: var(--bs-success);
        }
        .archive-icon {
            color: var(--bs-danger);
        }
        .media-icon {
            color: var(--bs-info);
        }

        /* 控制按钮区域样式 */
        .controls {
            display: flex;
            flex-direction: column;
            justify-content: center;
            gap: 1.5rem;
            padding: 1rem;
        }

        /* 按钮组样式 */
        .controls .btn-group {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }

        .controls .btn {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            padding: 0.75rem 1rem;
            border-radius: 0.75rem;
            position: relative;
            z-index: 1;
            transition: all 0.2s ease-in-out;
        }

        .controls .btn:hover {
            transform: translateX(2px);
            z-index: 2;
        }

        .controls .btn i {
            width: 1rem;
            text-align: center;
        }

        /* 刷新按钮样式 */
        .refresh-btn {
            padding: 0.25rem 0.5rem;
            display: inline-flex;
            align-items: center;
            gap: 0.375rem;
        }
        .refresh-btn i {
            transition: transform 0.3s ease;
        }
        .refresh-btn:hover i {
            transform: rotate(180deg);
        }

        /* 树形视图样式 */
        .tree-view {
            margin-left: 1.25rem;
            border-left: 1px dashed var(--bs-border-color);
            padding-left: 0.625rem;
        }
        .tree-toggle {
            cursor: pointer;
            padding: 0.125rem 0.375rem;
            margin-right: 0.375rem;
            color: var(--bs-gray-600);
            transition: transform 0.2s;
            display: inline-block;
        }
        .tree-toggle.expanded {
            transform: rotate(90deg);
        }
        .tree-content {
            display: none;
            margin-left: 1.25rem;
        }
        .tree-content.expanded {
            display: block;
        }

        /* 右键菜单样式 */
        .context-menu {
            position: fixed;
            z-index: 1050;
            background: var(--bs-body-bg);
            border: var(--bs-border-width) var(--bs-border-style) var(--bs-border-color);
            border-radius: var(--bs-border-radius);
            box-shadow: var(--bs-box-shadow);
            min-width: 10rem;
        }
        .context-menu-item {
            padding: 0.5rem 0.75rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--bs-body-color);
            transition: background-color 0.15s ease-in-out;
        }
        .context-menu-item:hover {
            background-color: var(--bs-gray-100);
            color: var(--bs-primary);
        }
        .context-menu-item i {
            width: 1rem;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-3">
        <div class="row">
            <!-- 源目录 -->
            <div class="col-5">
                <div class="directory-container">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h4>源目录</h4>
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-primary btn-sm" onclick="showCreateFolderModal('source')">
                                <i class="fas fa-folder-plus"></i>
                                <span>新建文件夹</span>
                            </button>
                            <button class="btn btn-outline-secondary btn-sm refresh-btn" onclick="loadDirectory('source')">
                                <i class="fas fa-sync-alt"></i>
                                <span>刷新</span>
                            </button>
                        </div>
                    </div>
                    <div id="source-list" class="file-list"></div>
                </div>
            </div>

            <!-- 控制按钮 -->
            <div class="col-2">
                <div class="controls">
                    <!-- 复制按钮组 -->
                    <div class="btn-group">
                        <button class="btn btn-primary" onclick="copyFiles('to_right')">
                            <i class="fas fa-arrow-right"></i> 复制到右侧
                        </button>
                        <button class="btn btn-primary" onclick="copyFiles('to_left')">
                            <i class="fas fa-arrow-left"></i> 复制到左侧
                        </button>
                    </div>
                    
                    <!-- 删除按钮组 -->
                    <div class="btn-group">
                        <button class="btn btn-danger" onclick="deleteSelected('source')">
                            <i class="fas fa-trash"></i> 删除左侧选中
                        </button>
                        <button class="btn btn-danger" onclick="deleteSelected('destination')">
                            <i class="fas fa-trash"></i> 删除右侧选中
                        </button>
                    </div>
                    
                    <!-- 工具按钮组 -->
                    <div class="btn-group">
                        <button class="btn btn-info" onclick="generateRsyncCommand()">
                            <i class="fas fa-terminal"></i> 生成rsync命令
                        </button>
                        <button class="btn btn-warning" onclick="showDeleteByNameModal()">
                            <i class="fas fa-search-minus"></i> 删除特定文件
                        </button>
                    </div>
                </div>
            </div>

            <!-- 目标目录 -->
            <div class="col-5">
                <div class="directory-container">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h4>目标目录</h4>
                        <div class="d-flex gap-2">
                            <button class="btn btn-outline-primary btn-sm" onclick="showCreateFolderModal('destination')">
                                <i class="fas fa-folder-plus"></i>
                                <span>新建文件夹</span>
                            </button>
                            <button class="btn btn-outline-secondary btn-sm refresh-btn" onclick="loadDirectory('destination')">
                                <i class="fas fa-sync-alt"></i>
                                <span>刷新</span>
                            </button>
                        </div>
                    </div>
                    <div id="destination-list" class="file-list"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Rsync命令模态框 -->
    <div class="modal fade" id="rsyncModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Rsync 命令</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">命令预览：</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="rsyncCommand" readonly>
                            <button class="btn btn-outline-primary" onclick="copyToClipboard()">
                                <i class="fas fa-copy"></i> 复制
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">选项：</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="optionArchive" checked onchange="updateRsyncCommand()">
                            <label class="form-check-label" for="optionArchive">
                                -a (归档模式，保留权限等)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="optionVerbose" checked onchange="updateRsyncCommand()">
                            <label class="form-check-label" for="optionVerbose">
                                -v (详细输出)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="optionProgress" onchange="updateRsyncCommand()">
                            <label class="form-check-label" for="optionProgress">
                                --progress (显示进度)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="optionDelete" onchange="updateRsyncCommand()">
                            <label class="form-check-label" for="optionDelete">
                                --delete (删除目标端不存在的文件)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="optionCompress" onchange="updateRsyncCommand()">
                            <label class="form-check-label" for="optionCompress">
                                -z (传输时压缩)
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="optionDryRun" onchange="updateRsyncCommand()">
                            <label class="form-check-label" for="optionDryRun">
                                --dry-run (模拟运行，不实际执行)
                            </label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">自定义选项：</label>
                        <div class="input-group">
                            <input type="text" class="form-control" id="customOptions" placeholder="例如: --exclude='*.tmp'" onchange="updateRsyncCommand()" onkeyup="updateRsyncCommand()">
                        </div>
                        <small class="text-muted">多个选项用空格分隔</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除特定文件模态框 -->
    <div class="modal fade" id="deleteByNameModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">删除特定文件</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">文件名：</label>
                        <input type="text" class="form-control" id="deleteFileName" placeholder="输入要删除的文件名">
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="deleteRecursive">
                            <label class="form-check-label" for="deleteRecursive">
                                递归搜索子文件夹
                            </label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">选择目录：</label>
                        <select class="form-select" id="deleteSide">
                            <option value="source">源目录</option>
                            <option value="destination">目标目录</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="deleteByName()">删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除结果模态框 -->
    <div class="modal fade" id="deleteResultModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">删除结果</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="deleteResultContent"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 新建文件夹模态框 -->
    <div class="modal fade" id="createFolderModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新建文件夹</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">文件夹名称：</label>
                        <input type="text" class="form-control" id="folderName" placeholder="输入文件夹名称">
                        <div class="form-text" id="createLocationHint"></div>
                    </div>
                    <input type="hidden" id="createFolderSide">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="createFolder()">创建</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 右键菜单 -->
    <div id="contextMenu" class="context-menu" style="display: none;">
        <div class="context-menu-item" onclick="selectFileForDeletion(event)">
            <i class="fas fa-trash text-danger"></i> 删除所有同名文件
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let selectedFiles = {
            source: null,
            destination: null
        };
        
        let currentFiles = {
            source: [],
            destination: []
        };

        function compareFiles(sourceFiles, destFiles) {
            const sourceMap = new Map(sourceFiles.map(f => [f.name, f]));
            const destMap = new Map(destFiles.map(f => [f.name, f]));
            
            sourceFiles.forEach(file => {
                const destFile = destMap.get(file.name);
                if (!destFile) {
                    file.status = 'missing';  // 在目标端不存在
                } else if (file.is_dir !== destFile.is_dir || 
                         (!file.is_dir && file.size !== destFile.size)) {
                    file.status = 'different';  // 文件类型或大小不同
                }
            });
            
            destFiles.forEach(file => {
                const sourceFile = sourceMap.get(file.name);
                if (!sourceFile) {
                    file.status = 'missing';  // 在源端不存在
                } else if (file.is_dir !== sourceFile.is_dir || 
                         (!file.is_dir && file.size !== sourceFile.size)) {
                    file.status = 'different';  // 文件类型或大小不同
                }
            });
        }

        function loadDirectory(side, path = '') {
            fetch(`/api/list?side=${side}&path=${path}&recursive=true`)
                .then(response => response.json())
                .then(data => {
                    currentFiles[side] = data;
                    
                    // 获取另一边的文件列表进行对比
                    const otherSide = side === 'source' ? 'destination' : 'source';
                    fetch(`/api/list?side=${otherSide}&path=${path}&recursive=true`)
                        .then(response => response.json())
                        .then(otherData => {
                            compareFiles(data, otherData);
                            renderFileList(side, data, path);
                        });
                });
        }

        function renderFileList(side, data, path) {
            const container = document.getElementById(`${side}-list`);
            container.innerHTML = '';
            
            data.forEach(item => {
                const itemElement = renderTreeItem(item, side);
                container.appendChild(itemElement);
            });
        }

        function getFileIcon(filename) {
            if (!filename) return '<i class="fas fa-file file-icon"></i>';
            
            const ext = filename.split('.').pop().toLowerCase();
            
            // 图片文件
            if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'].includes(ext)) {
                return '<i class="fas fa-image file-icon image-icon"></i>';
            }
            
            // 文档文件
            if (['doc', 'docx', 'pdf', 'txt', 'rtf', 'odt', 'pages'].includes(ext)) {
                return '<i class="fas fa-file-alt file-icon document-icon"></i>';
            }
            
            // 代码文件
            if (['py', 'js', 'html', 'css', 'java', 'cpp', 'c', 'h', 'php', 'rb', 'go', 'rs', 'swift'].includes(ext)) {
                return '<i class="fas fa-code file-icon code-icon"></i>';
            }
            
            // 压缩文件
            if (['zip', 'rar', '7z', 'tar', 'gz', 'bz2'].includes(ext)) {
                return '<i class="fas fa-file-archive file-icon archive-icon"></i>';
            }
            
            // 媒体文件
            if (['mp3', 'wav', 'ogg', 'mp4', 'avi', 'mov', 'wmv', 'flv'].includes(ext)) {
                return '<i class="fas fa-play-circle file-icon media-icon"></i>';
            }
            
            // Excel文件
            if (['xls', 'xlsx', 'csv'].includes(ext)) {
                return '<i class="fas fa-file-excel file-icon" style="color: #217346;"></i>';
            }
            
            // PowerPoint文件
            if (['ppt', 'pptx'].includes(ext)) {
                return '<i class="fas fa-file-powerpoint file-icon" style="color: #D24726;"></i>';
            }
            
            // 可执行文件
            if (['exe', 'msi', 'app', 'dmg'].includes(ext)) {
                return '<i class="fas fa-cog file-icon"></i>';
            }
            
            // 配置文件
            if (['json', 'xml', 'yaml', 'yml', 'ini', 'conf', 'config'].includes(ext)) {
                return '<i class="fas fa-cogs file-icon"></i>';
            }
            
            // 字体文件
            if (['ttf', 'otf', 'woff', 'woff2', 'eot'].includes(ext)) {
                return '<i class="fas fa-font file-icon"></i>';
            }
            
            // 链接文件
            if (['lnk', 'url', 'webloc'].includes(ext)) {
                return '<i class="fas fa-link file-icon"></i>';
            }

            // 默认文件图标
            return '<i class="fas fa-file file-icon"></i>';
        }

        function renderTreeItem(item, side, parentPath = '') {
            const wrapper = document.createElement('div');
            
            const itemDiv = document.createElement('div');
            itemDiv.className = 'file-item';
            if (item.status === 'missing') {
                itemDiv.classList.add('missing');
            } else if (item.status === 'different') {
                itemDiv.classList.add('different');
            }

            // 构建完整路径
            const fullPath = parentPath ? `${parentPath}/${item.name}` : item.name;

            // 添加展开/折叠按钮
            if (item.is_dir && item.children && item.children.length > 0) {
                const toggle = document.createElement('span');
                toggle.className = 'tree-toggle';
                toggle.innerHTML = '<i class="fas fa-chevron-right"></i>';
                toggle.onclick = (e) => {
                    e.stopPropagation();
                    const content = wrapper.querySelector('.tree-content');
                    const isExpanded = toggle.classList.toggle('expanded');
                    content.classList.toggle('expanded');
                    if (isExpanded) {
                        toggle.innerHTML = '<i class="fas fa-chevron-down"></i>';
                    } else {
                        toggle.innerHTML = '<i class="fas fa-chevron-right"></i>';
                    }
                };
                itemDiv.appendChild(toggle);
            }
            
            const icon = item.is_dir ? 
                '<i class="fas fa-folder file-icon folder-icon"></i>' : 
                getFileIcon(item.name);
            
            let itemInfo = `${icon} ${item.name}`;
            if (!item.is_dir) {
                const size = formatFileSize(item.size);
                itemInfo += `<span class="text-muted ms-2">(${size})</span>`;
            }
            
            const contentDiv = document.createElement('div');
            contentDiv.innerHTML = itemInfo;
            contentDiv.style.display = 'inline-block';
            itemDiv.appendChild(contentDiv);
            
            // 添加右键菜单事件
            itemDiv.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                showContextMenu(e, item.name, side);
            });
            
            // 修改这里，允许文件夹也可以被选中
            itemDiv.onclick = (e) => {
                // 如果点击的是展开/折叠按钮，不触发选择
                if (e.target.closest('.tree-toggle')) {
                    return;
                }
                selectFile(side, fullPath, itemDiv);
                
                // 如果是文件夹，同时触发展开/折叠
                if (item.is_dir && item.children && item.children.length > 0) {
                    const toggle = itemDiv.querySelector('.tree-toggle');
                    if (toggle) {
                        const content = wrapper.querySelector('.tree-content');
                        const isExpanded = toggle.classList.toggle('expanded');
                        content.classList.toggle('expanded');
                        if (isExpanded) {
                            toggle.innerHTML = '<i class="fas fa-chevron-down"></i>';
                        } else {
                            toggle.innerHTML = '<i class="fas fa-chevron-right"></i>';
                        }
                    }
                }
            };
            
            wrapper.appendChild(itemDiv);
            
            // 如果是目录且有子项，创建子项容器
            if (item.is_dir && item.children && item.children.length > 0) {
                const childrenContainer = document.createElement('div');
                childrenContainer.className = 'tree-content';
                childrenContainer.style.marginLeft = '20px';
                
                item.children.forEach(child => {
                    const childElement = renderTreeItem(child, side, fullPath);
                    childrenContainer.appendChild(childElement);
                });
                
                wrapper.appendChild(childrenContainer);
            }
            
            return wrapper;
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function selectFile(side, path, element) {
            // 清除之前的选择
            document.querySelectorAll(`#${side}-list .selected`).forEach(el => {
                el.classList.remove('selected');
            });
            
            // 确保路径包含完整的目录结构
            const fullPath = path;
            
            element.classList.add('selected');
            selectedFiles[side] = fullPath;
            console.log(`已选择文件: ${side} - ${fullPath}`); // 添加调试日志
        }

        function copyFiles(direction) {
            const source = direction === 'to_right' ? selectedFiles.source : selectedFiles.destination;
            const destination = direction === 'to_right' ? selectedFiles.destination || '' : selectedFiles.source || '';
            
            if (!source) {
                alert('请选择要复制的文件');
                return;
            }

            console.log(`正在复制: ${source} -> ${destination}`); // 添加调试日志

            fetch('/api/copy', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    source: source,
                    destination: destination,
                    direction: direction
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadDirectory('source');
                    loadDirectory('destination');
                } else {
                    alert('复制失败: ' + data.error);
                }
            });
        }

        function deleteSelected(side) {
            const path = selectedFiles[side];
            if (!path) {
                alert('请选择要删除的文件');
                return;
            }

            if (!confirm('确定要删除选中的文件吗？')) {
                return;
            }

            fetch('/api/delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    path: path,
                    side: side
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    loadDirectory(side);
                    selectedFiles[side] = null;
                } else {
                    alert('删除失败: ' + data.error);
                }
            });
        }

        function generateRsyncCommand() {
            if (!selectedFiles.source && !selectedFiles.destination) {
                alert('请先选择源文件或目标文件');
                return;
            }

            updateRsyncCommand();
            const modal = new bootstrap.Modal(document.getElementById('rsyncModal'));
            modal.show();
        }

        function updateRsyncCommand() {
            const options = [];
            if (document.getElementById('optionArchive').checked) options.push('-a');
            if (document.getElementById('optionVerbose').checked) options.push('-v');
            if (document.getElementById('optionProgress').checked) options.push('--progress');
            if (document.getElementById('optionDelete').checked) options.push('--delete');
            if (document.getElementById('optionCompress').checked) options.push('-z');
            if (document.getElementById('optionDryRun').checked) options.push('--dry-run');

            const customOptions = document.getElementById('customOptions').value.trim();
            if (customOptions) {
                options.push(customOptions);
            }

            const optionsStr = options.join(' ');
            
            let sourcePath = selectedFiles.source ? 
                `./source/${selectedFiles.source}` : './source/';
            let destPath = selectedFiles.destination ? 
                `./destination/${selectedFiles.destination}` : './destination/';

            // 如果是目录，确保路径以/结尾
            if (!sourcePath.endsWith('/')) sourcePath += '/';
            if (!destPath.endsWith('/')) destPath += '/';

            const command = `rsync ${optionsStr} ${sourcePath} ${destPath}`;
            document.getElementById('rsyncCommand').value = command;
        }

        function copyToClipboard() {
            const commandInput = document.getElementById('rsyncCommand');
            commandInput.select();
            document.execCommand('copy');
            
            // 显示复制成功提示
            const copyButton = document.querySelector('#rsyncCommand + button');
            const originalText = copyButton.innerHTML;
            copyButton.innerHTML = '<i class="fas fa-check"></i> 已复制';
            setTimeout(() => {
                copyButton.innerHTML = originalText;
            }, 2000);
        }

        function showDeleteByNameModal() {
            const modal = new bootstrap.Modal(document.getElementById('deleteByNameModal'));
            modal.show();
        }

        function deleteByName() {
            const filename = document.getElementById('deleteFileName').value.trim();
            if (!filename) {
                alert('请输入要删除的文件名');
                return;
            }

            const side = document.getElementById('deleteSide').value;
            const recursive = document.getElementById('deleteRecursive').checked;

            if (!confirm(`确定要删除${side === 'source' ? '源' : '目标'}目录中${recursive ? '及其子目录下' : ''}所有名为 "${filename}" 的文件吗？`)) {
                return;
            }

            fetch('/api/delete-by-name', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    filename: filename,
                    side: side,
                    recursive: recursive
                })
            })
            .then(response => response.json())
            .then(data => {
                let resultHtml = '<div class="mb-3">';
                if (data.deleted_files && data.deleted_files.length > 0) {
                    resultHtml += '<h6>已删除的文件：</h6><ul class="list-group">';
                    data.deleted_files.forEach(file => {
                        resultHtml += `<li class="list-group-item"><i class="fas fa-check text-success"></i> ${file}</li>`;
                    });
                    resultHtml += '</ul>';
                } else {
                    resultHtml += '<div class="alert alert-info">未找到匹配的文件</div>';
                }

                if (data.errors && data.errors.length > 0) {
                    resultHtml += '<h6 class="mt-3">错误信息：</h6><ul class="list-group">';
                    data.errors.forEach(error => {
                        resultHtml += `<li class="list-group-item"><i class="fas fa-exclamation-triangle text-danger"></i> ${error}</li>`;
                    });
                    resultHtml += '</ul>';
                }
                resultHtml += '</div>';

                document.getElementById('deleteResultContent').innerHTML = resultHtml;
                
                // 关闭删除对话框，显示结果对话框
                bootstrap.Modal.getInstance(document.getElementById('deleteByNameModal')).hide();
                const resultModal = new bootstrap.Modal(document.getElementById('deleteResultModal'));
                resultModal.show();

                // 刷新文件列表
                loadDirectory(side);
            })
            .catch(error => {
                alert('删除失败: ' + error);
            });
        }

        // 右键菜单相关函数
        let contextMenuTarget = null;

        function showContextMenu(e, filename, side) {
            const menu = document.getElementById('contextMenu');
            contextMenuTarget = { filename, side };
            
            // 设置菜单位置
            menu.style.display = 'block';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';
            
            // 点击其他地方时隐藏菜单
            document.addEventListener('click', hideContextMenu);
        }

        function hideContextMenu() {
            const menu = document.getElementById('contextMenu');
            menu.style.display = 'none';
            document.removeEventListener('click', hideContextMenu);
        }

        function selectFileForDeletion(e) {
            e.stopPropagation();
            if (contextMenuTarget) {
                const { filename, side } = contextMenuTarget;
                document.getElementById('deleteFileName').value = filename;
                document.getElementById('deleteSide').value = side;
                document.getElementById('deleteRecursive').checked = true;
                
                hideContextMenu();
                showDeleteByNameModal();
            }
        }

        // 修改showDeleteByNameModal函数，支持预填充
        function showDeleteByNameModal(filename, side) {
            if (filename) {
                document.getElementById('deleteFileName').value = filename;
            }
            if (side) {
                document.getElementById('deleteSide').value = side;
            }
            const modal = new bootstrap.Modal(document.getElementById('deleteByNameModal'));
            modal.show();
        }

        function showCreateFolderModal(side) {
            document.getElementById('createFolderSide').value = side;
            document.getElementById('folderName').value = '';
            
            // 更新创建位置提示
            const selectedPath = selectedFiles[side];
            const hint = document.getElementById('createLocationHint');
            
            if (selectedPath) {
                const findSelectedFile = (files, path) => {
                    for (const file of files) {
                        if (path === file.name || path.startsWith(file.name + '/')) {
                            return file;
                        }
                        if (file.children) {
                            const found = findSelectedFile(file.children, path);
                            if (found) return found;
                        }
                    }
                    return null;
                };
                
                const selectedFile = findSelectedFile(currentFiles[side], selectedPath);
                if (selectedFile && selectedFile.is_dir) {
                    hint.innerHTML = `<i class="fas fa-info-circle text-info"></i> 将在文件夹 "${selectedPath}" 中创建`;
                } else {
                    const parentPath = selectedPath.split('/').slice(0, -1).join('/');
                    hint.innerHTML = `<i class="fas fa-info-circle text-info"></i> 将在${parentPath ? `文件夹 "${parentPath}"` : '根目录'} 中创建`;
                }
            } else {
                hint.innerHTML = '<i class="fas fa-info-circle text-info"></i> 将在根目录中创建';
            }
            
            const modal = new bootstrap.Modal(document.getElementById('createFolderModal'));
            modal.show();
        }

        function createFolder() {
            const folderName = document.getElementById('folderName').value.trim();
            if (!folderName) {
                alert('请输入文件夹名称');
                return;
            }

            const side = document.getElementById('createFolderSide').value;
            let parentPath = '';
            
            // 获取选中的文件路径
            if (selectedFiles[side]) {
                // 在当前文件列表中查找选中的文件信息
                const findSelectedFile = (files, path) => {
                    for (const file of files) {
                        if (path === file.name || path.startsWith(file.name + '/')) {
                            return file;
                        }
                        if (file.children) {
                            const found = findSelectedFile(file.children, path);
                            if (found) return found;
                        }
                    }
                    return null;
                };
                
                const selectedFile = findSelectedFile(currentFiles[side], selectedFiles[side]);
                if (selectedFile && selectedFile.is_dir) {
                    // 如果选中的是文件夹，则在其中创建新文件夹
                    parentPath = selectedFiles[side];
                } else {
                    // 如果选中的是文件，则在其所在目录创建新文件夹
                    parentPath = selectedFiles[side].split('/').slice(0, -1).join('/');
                }
            }

            fetch('/api/create-folder', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    name: folderName,
                    side: side,
                    parent_path: parentPath
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    bootstrap.Modal.getInstance(document.getElementById('createFolderModal')).hide();
                    loadDirectory(side);
                } else {
                    alert('创建文件夹失败: ' + data.error);
                }
            })
            .catch(error => {
                alert('创建文件夹失败: ' + error);
            });
        }

        // 初始加载
        loadDirectory('source');
        loadDirectory('destination');
    </script>
</body>
</html> 